from django.urls import re_path

from stark.service.v1 import StarkHandler, Option, get_choice_text
from web import models
from web.utils.queryset import get_subnet_queryset


class HostRecordQueryHandler(StarkHandler):
    list_display = [
        get_choice_text('操作类型', 'operate_type'),
        'ip_address',
        'depart',
        'app_name',
        'location',
        'operate_person',
        'operate_date'
    ]

    search_group = [Option('depart') ]
    search_list = ['ip_address__contains', 'app_name__contains', 'location__contains']
    order_list = ['-operate_date']

    def get_urls(self):
        """
        二次路由分发
        :return:
        """
        patterns = [
            re_path(r'^list/$', self.wrapper(self.list_view), name=self.get_list_url_name),
            # re_path(r'^add/$', self.wrapper(self.add_view), name=self.get_add_url_name),
            # re_path(r'^change/(?P<pk>\d+)/$', self.wrapper(self.change_view),
            #         name=self.get_change_url_name),
            # re_path(r'^delete/(?P<host_id>\d+)/(?P<pk>\d+)/$', self.wrapper(self.delete_view),
            #         name=self.get_delete_url_name)
        ]
        patterns.extend(self.extra_url())
        return patterns

    def get_list_display(self, request, *args, **kwargs):
        """
        预留列表页面显示字段的钩子函数
        :return:
        """
        value = []
        if self.list_display:
            value.extend(self.list_display)
        return value

    def get_add_btn(self, request, *args, **kwargs):
        return None

    def get_queryset(self, request, *args, **kwargs):
        current_user_id = request.session['user_info']['user_id']
        user_object = models.UserInfo.objects.filter(id=current_user_id).first()
        queryset = self.model_class.objects.all()
        if not user_object.is_depart:
            return queryset
        subnet_queryset_list = get_subnet_queryset().filter(depart=user_object.depart)
        subnet_list = [item.id for item in subnet_queryset_list]
        queryset = queryset.filter(ip_subnet_id__in=subnet_list)
        return queryset
